package com.aptemo.webetek.server.handlers;

import com.aptemo.webetek.client.commands.Action;
import com.aptemo.webetek.client.commands.impl.JoinGroupAction;
import com.aptemo.webetek.client.enums.EnumUserRole;
import com.aptemo.webetek.client.enums.EnumUserStatus;
import com.aptemo.webetek.client.exceptions.BackendException;
import com.aptemo.webetek.client.exceptions.WebetekLoginException;
import com.aptemo.webetek.client.exceptions.BackendException.EErrorCodes;
import com.aptemo.webetek.server.datastore.DataStoreAPI;
import com.aptemo.webetek.shared.UserBean;

public class JoinGroupHandler
		extends ActionHandler<JoinGroupAction, UserBean>
{

	public JoinGroupHandler(DataStoreAPI service)
	{
		super(service);
	}

	public Class<? extends Action<?>> getActionType()
	{
		return JoinGroupAction.class;
	}

	@Override
	public UserBean invoke(JoinGroupAction action) throws BackendException, WebetekLoginException
	{
		utils.checkLogin();

		String email = userService.getCurrentUser().getEmail();

		if (utils.isTeamMember(action.getTeamId(), email))
		{
			throw new BackendException(EErrorCodes.PLAYER_EXISTS_ALREADY);
		}

		// create new player
		UserBean ub = dataService.createPlayer(action.getTeamId(), email, EnumUserStatus.JOINING, EnumUserRole.GAMER, 0.0);

		// boolean result = dataService.joinToGroup(action.getUserGroupId(),
		// action.getNote(), action.getSubject());

		// / TODO email notification...
		String content = "User '" + email + "' wants to join your group. ";
		content += "\r\n";
		content += "\r\n";

		// approve / reject
		String link = this.getServletUrl() + "/webetek/invite?id=" + ub.getKey();
		String approveLink = link + "&method=approve";
		content += "You can approve player by clicking the folowing link ";
		content += "\r\n";
		content += approveLink;

		String rejectLink = link + "&method=reject";
		content += "\r\n\r\n";
		content += "Or you can reject request here ";
		content += "\r\n";
		content += rejectLink;

		content += "\r\n";
		content += "\r\n";
		content += "An user note:";
		content += "\r\n";
		content += action.getNote();
		content += "\r\n";
		content += "\r\n";

		// farewell
		String farewell = "\r\n\r\n" + "Webetek Online (2010)"; // action.getFarewell();
		farewell += "\r\n" + "http://webetek.appspot.com/#group-" + action.getTeamId();
		content += farewell;

		// get team owner (recipient)
		String to = dataService.getTeam(action.getTeamId()).getOwnerEmail();
		createEmailSenderTask("", to, "", action.getSubject(), content);

		return ub;
	}

}
